<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <!-- 添加角色 -->
      <el-row>
        <el-col>
          <el-button type=primary @click='addRolesBtn'>添加角色</el-button>
        </el-col>
      </el-row>

      <!-- 角色列表区 -->
      <el-table :data='rolelist' border stripe>
        <el-table-column type="expand">
          <template slot-scope='scope'>
            <el-row :class='["borderBottom",i1===0?"borderTop":""]' v-for='(item1,i1) in scope.row.children'
              :key='item1.id' class="vcenter">
              <!-- 渲染一级权限 -->
              <el-col :span='5'>
                <el-tag @close='removeRightById(scope.row,item1.id)' closable>{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二级和三级权限 -->
              <el-col :span='19'>
                <!-- 循环渲染二级权限 -->
                <el-row class="vcenter" :class='[i2===0?"":"borderTop"]' v-for='(item2,i2) in item1.children'
                  :key='item2.id'>
                  <el-col :span='6'>
                    <el-tag @close='removeRightById(scope.row,item2.id)' closable type='success'>{{item2.authName}}
                    </el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span='18'>
                    <el-tag @close='removeRightById(scope.row,item3.id)' closable style="margin-right: 4px;"
                      type='warning' v-for='(item3,i3) in item2.children' :key='item3.id'>{{item3.authName}}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type='index'></el-table-column>
        <el-table-column label='角色名称' prop='roleName'></el-table-column>
        <el-table-column label='角色描述' prop='roleDesc'></el-table-column>
        <el-table-column label='操作' width='300px'>
          <template slot-scope='scope'>
            <el-button type="primary" icon="el-icon-edit" size='mini' @click='editRolesBtn(scope.row.id)'>编辑</el-button>
            <el-button type="danger" icon="el-icon-delete" size='mini' @click='deleteRole(scope.row.id)'>删除</el-button>
            <el-button type="warning" icon="el-icon-setting" size='mini' @click='showSetRightDialog(scope.row.id)'>分配权限
            </el-button>
          </template>
        </el-table-column>
      </el-table>

    </el-card>

    <!-- 添加角色对话框 -->
    <el-dialog title="添加" :visible.sync="addUserdialogVisible" width="50%">
      <el-form ref="addUserRef" :model="addUser" label-width="80px" :rules='addUserRules'>
        <el-form-item label="角色名称" prop='roleName'>
          <el-input v-model="addUser.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="addUser.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click='cancelAddRoles'>取 消</el-button>
        <el-button type="primary" @click='addRoles'>确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑角色对话框 -->
    <el-dialog title="编辑" :visible.sync="editUserdialogVisible" width="50%">
      <el-form ref="editUserRef" :model="editRoles" label-width="80px">
        <el-form-item label="角色ID">
          <el-input v-model="editRoles.roleId" disabled></el-input>
        </el-form-item>
        <el-form-item label="角色名称">
          <el-input v-model="editRoles.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="editRoles.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click='cancelEditRoles'>取 消</el-button>
        <el-button type="primary" @click='quedingeditRoles'>确 定</el-button>
      </span>
    </el-dialog>


    <!--分配权限的对话框  -->
    <el-dialog title="分配权限" :visible.sync="setRightDialogVisible" width="50%" @close="setRightDialogClosed">
      <el-tree ref='treeRef' :data="rightsList" :props="treeProps" show-checkbox node-key="id"
        :default-expand-all='true' :default-checked-keys='defKeys'></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click='allotRights'>确 定</el-button>
      </span>
    </el-dialog>


  </div>
</template>

<script>
  export default {
    name: '',
    data() {
      return {
        // 角色列表数据
        rolelist: [],
        // 控制添加角色对话框
        addUserdialogVisible: false,
        // 添加角色数据收集
        addUser: {
          roleName: '',
          roleDesc: ''
        },
        // 添加角色收集数据校验规则
        addUserRules: {
          roleName: [
            { required: true, message: '角色名称不能为空!', trigger: 'blur' }
          ]
        },
        // 编辑对话框控制显示
        editUserdialogVisible: false,
        // 编辑对话框数据
        editRoles: {},
        // 控制分配权限对话框
        setRightDialogVisible: false,
        // 所有权限的数据
        rightsList: [],
        // 属性控件配置信息
        treeProps: {
          label: 'authName',
          children: 'children'
        },
        // 默认选中的结点id数组
        defKeys: [],
        // 当前即将分配权限的角色id
        roleId: ''
      }
    },
    created() {
      this.getRolesList()
    },
    methods: {
      // 获取所有角色的列表
      async getRolesList() {
        const { data: res } = await this.$http.get('/roles')
        if (res.meta.status !== 200) { return this.$message({ type: 'error', message: '获取角色列表失败' }) }
        this.rolelist = res.data
        // console.log(this.rolelist);
      },
      // 添加角色
      addRolesBtn() {
        this.addUserdialogVisible = true
      },
      // 撤销添加角色
      cancelAddRoles() {
        this.addUserdialogVisible = false
        this.$refs.addUserRef.resetFields()
        this.$message({ type: 'error', message: '已经撤销添加角色' })
      },
      // 添加新角色
      async addRoles() {
        const { data: res } = await this.$http.post('/roles', this.addUser)
        if (res.meta.status !== 201) {
          this.addUserdialogVisible = false
          return this.$message({ type: 'error', message: '添加角色失败' })
        }
        this.$message({ type: 'success', message: '添加新角色成功' })
        this.addUserdialogVisible = false
        this.$refs.addUserRef.resetFields()
        this.getRolesList()
      },
      // 点击编辑按钮 根绝id查找角色
      async editRolesBtn(id) {
        const { data: res } = await this.$http.get('/roles/' + id)
        if (res.meta.status !== 200) { return this.$message({ type: 'error', message: '获取角色失败' }) }
        this.editRoles = res.data
        this.editUserdialogVisible = true
      },
      // 取消编辑
      cancelEditRoles() {
        this.$refs.editUserRef.resetFields()
        this.$message({ type: 'error', message: '取消编辑' })
        this.editUserdialogVisible = false
      },
      // 确定编辑
      async quedingeditRoles() {
        const { data: res } = await this.$http.put(`/roles/${this.editRoles.roleId}`, {
          roleName: this.editRoles.roleName,
          roleDesc: this.editRoles.roleDesc
        })
        if (res.meta.status !== 200) {
          this.editUserdialogVisible = false
          return this.$message({ type: 'error', message: '编辑角色失败' })
        }
        this.$message({ type: 'success', message: '编辑角色成功' })
        this.editUserdialogVisible = false
        this.$refs.editUserRef.resetFields()
        this.getRolesList()
      },
      // 删除角色按钮事件
      deleteRole(id) {
        this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          // 确定删除 发送ajax请求 删除角色  然后刷新角色列表
          const { data: res } = await this.$http.delete('/roles/' + id)
          console.log(res); D
          if (res.meta.status !== 200) { return this.$message({ type: 'error', message: '删除失败' }) }
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          this.getRolesList()
        }).catch((e) => {
          console.log(e);
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
      //  根据id删除对应的权限
      async removeRightById(role, rightId) {
        // 弹框提示用户是否要删除
        const confirmResult = await this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err => err)
        if (confirmResult !== 'confirm') { return this.$message({ type: 'info', message: '取消删除' }) }
        const { data: res } = await this.$http.delete(`/roles/${role.id}/rights/${rightId}`)
        if (res.meta.status !== 200) { return this.$message({ type: 'error', message: '删除失败' }) }
        // this.getRolesList()
        // 为当前角色信息重新复制权限
        role.children = res.data
        this.$message({ type: 'success', message: '确认删除' })
      },
      // 展示分配权限的对话框
      async showSetRightDialog(id) {
        this.roleId = id
        this.defKeysPush(id)
        // 获取所有权限的数据
        const { data: res } = await this.$http.get('rights/tree')
        if (res.meta.status !== 200) { return this.$message({ type: 'error', message: '获取权限数据失败' }) }
        // 获取的权限数据保存到data中
        this.rightsList = res.data
        // console.log(this.rightsList);
        this.setRightDialogVisible = true
      },
      // 给默认权限id数组push数据
      defKeysPush(id) {
        this.defKeys = []
        let obj = this.rolelist.find(item => item.id === id)
        for (let i of obj.children) {
          for (let j of i.children) {
            for (let k of j.children) {
              this.defKeys.push(k.id)
            }
          }
        }
      },
      // 监听分配权限对话框的关闭事件
      setRightDialogClosed() {
        this.defKeys = []
      },
      // 为角色分配权限
      async allotRights() {
        const keys = [
          ...this.$refs.treeRef.getCheckedKeys(),
          ...this.$refs.treeRef.getHalfCheckedKeys()
        ]
        const idStr = keys.join(',')
        const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, { rids: idStr })
        if (res.meta.status !== 200) { return this.$message({ type: 'error', message: '分配权限数据失败' }) }
        this.$message({ type: 'success', message: '分配权限数据成功' })
        this.getRolesList()
        this.setRightDialogVisible = false
      }
    },
    components: {

    }
  }
</script>

<style scoped>
  .el-tag {
    margin: 7px 0;
  }

  .vcenter {
    display: flex;
    align-items: center;
  }
</style>